package org.jbch.shittim;

import java.util.List;
import org.jbch.shittim.Utils.ServiceToken;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.Html;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class secondActivity extends Activity implements OnItemClickListener, OnClickListener, ServiceConnection, OnSeekBarChangeListener{
	Handler handler;
 
    JbchAdapter adapter;
    private ListView broadListView;
//	private List<ShittimInfo> shittimInfo;
    private ProgressDialog loagindDialog; // Loading Dialog
    private static int mLastListPosCourse = -1;
    private static int mLastListPosFine = -1;
    private static int mProgressMaxVal= 0;
	private String LOG_TAG = "jbchLog";
	private ImageButton previousBtn;
	private ImageButton nextBtn;
	private ImageButton playBtn;
	private ImageButton networkRefreshBtn;
	private ImageButton nowplayingMsgBarCloseBtn;
    private ServiceToken mToken;
    private SeekBar mProgress; 
    private TextView txtNowplayingMsg ;
    private int rowIdx;
    final int ONE = 0;
    final int TWO = 1;
//    final int THREE = 2;

	private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			int cmd = intent.getIntExtra("mpMaxVal", 0);
			int state = intent.getIntExtra("state", 0);
			int arryIdx = intent.getIntExtra("arryIdx", 0);
			String id = intent.getStringExtra("id");
			String desc = intent.getStringExtra("desc");
			int mResId = intent.getIntExtra("resId", R.drawable.thum_bg);
			int parsingEnd = intent.getIntExtra("parsingEnd", 0);
			int songListDisp = intent.getIntExtra("songListDisp", 0);
			int networkState = intent.getIntExtra("networkState", 0);
			
			if (BackgroundAudioService.ACTION_BASE_INFO_PARSING_END.equals(action)) {
				
				if(parsingEnd==0){
					showProgressbar(true);
				}else if(parsingEnd==1){  
					showProgressbar(false);
				}  
				if(songListDisp==1){
					updateSongList();   
				}
				
				mProgress.setMax(mProgressMaxVal);
			} else if (BackgroundAudioService.ACTION_PROGRESS_MAX_VALUE
					.equals(action)) {
				mProgressMaxVal = cmd;
				mProgress.setMax(cmd);
			}else if (BackgroundAudioService.ACTION_BROAD_PLAY_STATE.equals(action)) {
				Utils.setPlayBtnState(secondActivity.this, state, R.id.playBtn);
			}else if (BackgroundAudioService.ACTION_BROAD_PLAY_ON_LIST.equals(action)) {

				updateListRowImage(mResId, arryIdx);
 
			}else if (BackgroundAudioService.ACTION_NETWORK_STATE_INFO.equals(action)) {

				updateNetworkState(networkState);
 
			}
		}

	};
    
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		Log.i(LOG_TAG,"onCreate()");
	    super.onCreate(savedInstanceState);
	    handler = new Handler();

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // service에 바운드 되면서 
        mToken = Utils.bindToService(this, this);
        
	    setContentView(R.layout.second);

	    Utils.updateButtonBar(this, R.id.tab02);
	    
	    broadListView = (ListView)findViewById(R.id.broadList); 
	    broadListView.setOnItemClickListener(this);
	    broadListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	    
//	    broadListView.setSelector( new PaintDrawable( 0xffff0000 )  ) ;
	    
		previousBtn = (ImageButton)findViewById(R.id.preBtn);
		nextBtn = (ImageButton)findViewById(R.id.nextBtn);
		playBtn = (ImageButton)findViewById(R.id.playBtn);
		networkRefreshBtn= (ImageButton)findViewById(R.id.network_refresh_btn);
		nowplayingMsgBarCloseBtn= (ImageButton)findViewById(R.id.nowplayingMsgBarClsBtn);
		txtNowplayingMsg= (TextView) findViewById(R.id.nowplayingMsg);
		txtNowplayingMsg.setSelected(true);
		
		previousBtn.setOnClickListener(this); 
		nextBtn.setOnClickListener(this);
		playBtn.setOnClickListener(this);
		networkRefreshBtn.setOnClickListener(this);
		nowplayingMsgBarCloseBtn.setOnClickListener(this);
   
		IntentFilter commandFilter = new IntentFilter();
        commandFilter.addAction(BackgroundAudioService.ACTION_BASE_INFO_PARSING_END);
        commandFilter.addAction(BackgroundAudioService.ACTION_PROGRESS_MAX_VALUE);
        commandFilter.addAction(BackgroundAudioService.ACTION_BROAD_PLAY_STATE);
        commandFilter.addAction(BackgroundAudioService.ACTION_BROAD_PLAY_ON_LIST);
        commandFilter.addAction(BackgroundAudioService.ACTION_NETWORK_STATE_INFO);
        
        registerReceiver(mIntentReceiver, commandFilter);
        
        mProgress = (SeekBar)findViewById(R.id.bottomSeekbar); 
        mProgress.setOnSeekBarChangeListener(this);
        
        mMediaplayerHandler.sendEmptyMessageDelayed(0, 2000);

		int playBtnState = Utils.getIntPref(this, "playBtnState", 0);
		Utils.setPlayBtnState(this, playBtnState, R.id.playBtn);
		
		registerForContextMenu(broadListView);
 
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { 
		menu.setHeaderIcon(R.drawable.ic_cxt_header01);
        menu.setHeaderTitle(R.string.app_name);
          
        LayoutInflater layout = getLayoutInflater();
        View cv = layout.inflate(R.layout.context_header, null);
        menu.setHeaderView(cv);
        
        menu.add(Menu.NONE, ONE, Menu.NONE, R.string.menu_items01);	//다운로드
        menu.add(Menu.NONE, TWO, Menu.NONE, R.string.menu_items02);	//공유
        super.onCreateContextMenu(menu, v, menuInfo);
         
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo menuInfo =
                (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		rowIdx = menuInfo.position;
		switch (item.getItemId()) {
        case ONE:
//             Toast.makeText(this, "["+rowIdx+"] ONE-제목:"+Utils.getPlayList().get(rowIdx).getmTitle()+"/아이디:"+Utils.getPlayList().get(rowIdx).getmId() , Toast.LENGTH_SHORT).show();
            break;
        case TWO:
//            Toast.makeText(this, "["+rowIdx+"] TWO-제목:"+Utils.getPlayList().get(rowIdx).getmTitle()+"/아이디:"+Utils.getPlayList().get(rowIdx).getmId() , Toast.LENGTH_SHORT).show();
           break;
        default:
            break;
        }
		
		return super.onContextItemSelected(item);
	}
//  
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.preBtn:
			try {
				Utils.sService.getmBinder().setSeekTo(0);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			 
            intent = new Intent(BackgroundAudioService.ACTION_BROAD_PREV);
            intent.setClass(this, BackgroundAudioService.class);
            startService(intent);
			
			break;

		case R.id.nextBtn:

			try {
				Utils.sService.getmBinder().setSeekTo(0);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
            intent = new Intent(BackgroundAudioService.ACTION_BROAD_NEXT);
            intent.setClass(this, BackgroundAudioService.class);
            startService(intent);
             
			break;

		case R.id.playBtn:

            intent = new Intent(BackgroundAudioService.ACTION_BROAD_PLAY);
            intent.setClass(this, BackgroundAudioService.class);
            startService(intent); 
            
			break;


		case R.id.network_refresh_btn:

			Toast.makeText(this, "새로고침 !", Toast.LENGTH_SHORT).show();
            intent = new Intent(BackgroundAudioService.ACTION_BASE_INFO_CALL);
            intent.setClass(this, BackgroundAudioService.class);
            startService(intent); 
 
            
			break;  
		case R.id.nowplayingMsgBarClsBtn:

			Toast.makeText(this, "nowplayingMsgBarClsBtn_close !", Toast.LENGTH_SHORT).show();
	        updatenowplayingMsgBar(0);

			break;  
		}
		
	}
	

    void showProgressbar(boolean isShow) {
        /* ProgressDialog */
    	
    	if(isShow){

//    		Log.i(LOG_TAG,"----------->showProgressbar:"+isShow);
            loagindDialog = ProgressDialog.show(this, "Connecting",
                    "Loading. Please wait...", true, false);
             	
    	}else{

    		try{
                loagindDialog.dismiss(); // 다이얼로그 삭제
    			
    		}catch(Exception ex){
    			
    		}
    	}
    }
 

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE , Utils.MENU1 , Menu.NONE , "새로고침");
		menu.add(Menu.NONE , Utils.MENU2 ,  Menu.NONE , "환경설정");
        return true;
    }  

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
		case Utils.MENU1:

			Utils.activateTab(this, R.id.tab02);

			
			break;

		default:
			break;
		}
		
		return false; 
		
	}

	

    @Override
    public void onSaveInstanceState(Bundle outcicle) {
        // need to store the selected item so we don't lose it in case
        // of an orientation switch. Otherwise we could lose it while
        // in the middle of specifying a playlist to add the item to.
    	
//        outcicle.putString("selectedalbum", mCurrentAlbumId);
//        outcicle.putString("selectedalbumname", mCurrentAlbumName);
//        outcicle.putString("selectedartist", mCurrentArtistId);
//        outcicle.putString("selectedartistname", mCurrentArtistName);
        super.onSaveInstanceState(outcicle);
    }


    @Override
    public void onDestroy() {
		Log.i(LOG_TAG,"onDestroy()");
		try {
			if (Utils.sService.getmBinder().isPlaying()) {
				Utils.setIntPref(this, "playBtnState", 1);
			}else{
				Utils.setIntPref(this, "playBtnState", 0);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
        if (broadListView != null) {
            mLastListPosCourse = broadListView.getFirstVisiblePosition();
            View cv = broadListView.getChildAt(0);
            if (cv != null) {
                mLastListPosFine = cv.getTop();
            }
        } 
        Utils.unbindFromService(mToken);
        unregisterReceiver(mIntentReceiver);
        mMediaplayerHandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
    
    @Override
    public void onResume() {
        super.onResume();

//		int playBtnState = Utils.getIntPref(this, "playBtnState", 0);
//		Utils.setPlayBtnState(this, playBtnState, R.id.playBtn);
		

    	
    }

    @Override
    public void onPause() {
        super.onPause();

//		try {
//			if (Utils.sService.getmBinder().isPlaying()) {
//				Utils.setIntPref(this, "playBtnState", 1);
//			}else{
//				Utils.setIntPref(this, "playBtnState", 0);
//			}
//		} catch (RemoteException e) {
//			e.printStackTrace();
//		}
		
        Toast.makeText(this, "onPause!", Toast.LENGTH_SHORT).show();
  
//        if (broadListView != null) {
//            mLastListPosCourse = broadListView.getFirstVisiblePosition();
//            View cv = broadListView.getChildAt(0);
//            if (cv != null) {
//                mLastListPosFine = cv.getTop();
//            }
//        }
        
    }
    
	 

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
 
	      Intent goActivity =new Intent(this,SecondDetailActivity.class);
	      goActivity.putExtra("rowIdx", position);
	      startActivity(goActivity); 
	}  

	// Utils 로 빼서 작업
	public void updateNetworkState(int networkState) {

		View v1 = (ListView)findViewById(R.id.broadList);
		View v2 = (LinearLayout)findViewById(R.id.nowplayingBar);
		View v3 = (RelativeLayout)findViewById(R.id.network_refresh);
		
		if(networkState==0){
			v1.setVisibility(View.GONE);
			v2.setVisibility(View.GONE);
			v3.setVisibility(View.VISIBLE);
		}else{
			v1.setVisibility(View.VISIBLE);
			v2.setVisibility(View.VISIBLE);
			v3.setVisibility(View.GONE);
		}
	}

	public void updatenowplayingMsgBar(int state) {
//
//		View v1 = (ListView)findViewById(R.id.broadList);
//		View v2 = (LinearLayout)findViewById(R.id.nowplayingBar);
//		View v3 = (RelativeLayout)findViewById(R.id.network_refresh);
//      
//
		View v = (RelativeLayout)findViewById(R.id.nowplayingMsgBar);
		
		if(state==0){
			v.setVisibility(View.GONE);
		}else{

			//txtNowplayingMsg.setText("XXXXXXXXXXXXXXXXXXXXXXX111fadsfasdfasdfsdafasdfsadfasdfsadfsdafasdfasdfasdfasdfadsfasd2334");
			
			v.setVisibility(View.VISIBLE);
		}
	}
	
	
	
	public void updateListRowImage(int resId , int arryIdx){
    	ImageView iv;
    	ImageView iv2;
    	TextView txtV; 
//    	LinearLayout linearLayout;
    	View lv1;

//		Log.i("jbchLog",">>>>>>>>>>>>>>>>>>>>> arryIdx:"+arryIdx);
    	
    	String desc =Utils.getPlayList().get(arryIdx).getmDesc();
    	String id=Utils.getPlayList().get(arryIdx).getmId();

//		Log.i("jbchLog",">>>>>>>>>>>>>>>>>>>>> id:"+id);
		
    	txtNowplayingMsg.setText(Html.fromHtml(desc));
		
        if (broadListView != null) {
        	int listCount = broadListView.getChildCount();
        	for(int z=0 ; z<listCount; z++){
        		iv = (ImageView)(broadListView.getChildAt(z).findViewById(R.id.list_image));
        		iv2 = (ImageView)(broadListView.getChildAt(z).findViewById(R.id.list_more_image));
        		txtV = (TextView)(broadListView.getChildAt(z).findViewById(R.id.board_id));
        		lv1 = (LinearLayout)(broadListView.getChildAt(z).findViewById(R.id.linearLayout1));//findViewById(R.id.linearLayout1);
//        		Log.i("jbchLog","updateListRowImage-txtV.getText() : "+txtV.getText()+"/id:"+ id );
        		if(txtV.getText().equals(id)){ 
            		iv.setImageResource(resId);
            		iv2.setImageResource(R.drawable.ic_list_more_selected);
            		lv1.setBackgroundResource(R.drawable.thum_bg);
//            		broadListView.getChildAt(z).setBackgroundColor(Color.rgb(85,135,237));
            		
        		}else{
            		iv.setImageResource(0);	//R.drawable.thum_bg);
            		iv2.setImageResource(R.drawable.ic_list_more);
            		lv1.setBackgroundResource(R.drawable.thum_bg2);
//            		broadListView.getChildAt(z).setBackgroundColor(Color.TRANSPARENT);
        		}

        		iv.refreshDrawableState();    
        		iv.invalidate();
        		

        		lv1.refreshDrawableState();    
        		lv1.invalidate();
        		
        		
        	} 
        }
        
        updatenowplayingMsgBar(1);
          
	} 

	public void updateSongList() {

		List<ShittimInfo> plist = Utils.getPlayList();
		adapter = new JbchAdapter(getApplicationContext(), R.id.broadList, plist);
		broadListView.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		if (mLastListPosCourse >= 0) {
			broadListView.setSelectionFromTop(mLastListPosCourse,
					mLastListPosFine);
			mLastListPosCourse = -1;
		}
	}

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {

		Utils.updateNowPlaying(this);
		
	}

	@Override
	public void onServiceDisconnected(ComponentName name) {
        finish();
	}
	 

	Handler mMediaplayerHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			try {
				if (Utils.sService.getmBinder().isPlaying()) {
					
					mProgress.setProgress(Utils.sService.getmBinder().getMpCurrentPosition());
				}
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			mMediaplayerHandler.sendEmptyMessageDelayed(0, 2000);
		}
	};

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		
		if(fromUser){
			try {
				Utils.sService.getmBinder().setSeekTo(progress);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}




	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		try {
			if (Utils.sService.getmBinder().isPlaying()) {
				Utils.sService.getmBinder().pause();
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}




	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	
}
